<?php

namespace App\Controller\Pay;

use App\Base\BaseController4Restful;
use App\Base\BaseController4Web;
use App\Entity\DbLog;
use App\Event\PayEvent;
use App\Repository\MoneyPayOrderRepository;
use App\Service\PayService;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;


class CallBackController extends BaseController4Web
{
    /**
     * @Route("/pay/cb/ali", name="AppPayCallBackAliPay")
     */
    public function AppPayCallBackAliPay(PayService $ps)
    {
        if (!$sn = $this->getParamRequired("out_trade_no")) {
            $this->logger->info("whereismysn");
            die("whereismysn");
        }
        if (!$from = $this->getParamRequired("passback_params")) {
            $this->logger->info("whereareufrom");
            die("whereareufrom");
        }
        switch ($from) {
            case "insure":
                $ps->dealWithPayCallBackInsure($sn);
                break;
            case "taskhire":
                $ps->dealWithCallBackTaskHire($sn);
                break;
            case "order":
                $ps->dealWithCallBackOrder($sn);
                break;
            case "charge":
                $ps->dealWithCallBackUserCharge($sn);
                break;
        }
        return $this->json_out(200, "OK");
    }

    /**
     * @Route("/pay/cb/wx", name="AppPayCallBackWeChat")
     */
    public function AppPayCallBackWeChat(
        PayService $ps,
        Request $request,
        MoneyPayOrderRepository $moneyPayOrderRepository,
        EventDispatcherInterface $dispatcher
    )
    {
        $postStr = file_get_contents('php://input');
        //禁止引用外部xml实体
        $bPreviousValue = libxml_disable_entity_loader(true);
        $array_data = json_decode(json_encode(simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        libxml_disable_entity_loader($bPreviousValue);

        if (isset($array_data['return_code']) and $array_data['return_code'] == 'SUCCESS') {
            //todo 检验来源的合法性
            $sn = $array_data["out_trade_no"];//取出回调码
            $from = $array_data["attach"];//取出预留参数

            $payOrder = $moneyPayOrderRepository->findOneBy(array("sn" => $sn));

            $event = new PayEvent($payOrder);
            switch ($from) {
                case "order":
                    $dispatcher->dispatch($event,PayEvent::PAY_ORDER);
                    break;
                case "charge":
                    $dispatcher->dispatch($event,PayEvent::PAY_CHARGE);
                    break;
            }
            return $this->json_out(200, "OK");
        }
        //数据监听模式不能拿到正常的数据返回，应该注销以下内容
//        echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        die;
    }
}
